/**
 * Project Name:kany-utils
 * File Name:TaskUtils.java
 * Package Name:me.kany.utils.springutils.task
 * Date:2016年9月20日下午10:21:57
 * Copyright (c) 2016, Jason.Wang All Rights Reserved.
 */
package me.kany.utils.springutils.task;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import me.kany.utils.springutils.AopTargetUtils;
import me.kany.utils.springutils.SpringUtils;
import me.kany.utils.springutils.task.model.ScheduleJob;


/**
 * ClassName:TaskUtils<br/>
 * Function: 任务获取的方法，主要用反射实现<br/>
 * Date:2016年9月14日上午11:45:05<br/>
 * 
 * @author Jason.Wang
 * @version 1.0
 * @since JDK1.7
 * @see
 */
public class TaskUtils {

	private static Logger logger = LoggerFactory.getLogger(TaskUtils.class.getCanonicalName());

	/**
	 * 通过反射调用scheduleJob中定义的方法
	 * 
	 * @param scheduleJob
	 */
	public static void invokMethod(ScheduleJob scheduleJob) {
		Object object = null;
		Class<?> clazz = null;
		if (StringUtils.isNotBlank(scheduleJob.getSpringId())) {
			try {
				object = SpringUtils.getBean(scheduleJob.getSpringId());
				object = AopTargetUtils.getTarget(object);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (StringUtils.isNotBlank(scheduleJob.getBeanClass())) {
			try {
				clazz = Class.forName(scheduleJob.getBeanClass());
				object = clazz.newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		if (object == null) {
			logger.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功，请检查是否配置正确！！！");
			return;
		}
		clazz = object.getClass();
		Method method = null;
		try {
			method = clazz.getDeclaredMethod(scheduleJob.getMethodName());
		} catch (NoSuchMethodException e) {
			logger.error("任务名称 = [" + scheduleJob.getJobName() + "]---------------未启动成功，方法名设置错误！！！");
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		if (method != null) {
			try {
				method.invoke(object);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		System.out.println("任务名称 = [" + scheduleJob.getJobName() + "]----------启动成功");
	}
}
